const Router = require('koa-router')
const axios = require('axios')
const MemoryFs = require('memory-fs')
const webpack = require('webpack')
const fs = require('fs')
const path = require('path')
const VueServerRenderer = require('vue-server-renderer')

const serverConfig = require('../../webpack.server.config')
const serverCompiler = webpack(serverConfig)
const serverRender = require('./server-render')
const mfs = new MemoryFs()
// 指定使用的文件系统
serverCompiler.outputFileSystem = mfs

let bundle
serverCompiler.watch({}, async (err, status) => {
    if(err) throw err
    status = status.toJson()
    status.errors.forEach(err => console.log(err))
    status.warnings.forEach(warn => console.warn(warn))
    // vue-ssr-server-bundle.json 这个文件是服务端webpack [const VueServerPlugin = require('vue-server-renderer/server-plugin')] 这个插件生成的，默认名字就是这个
    const bundlePath = path.join(
        serverConfig.output.path,
        'vue-ssr-server-bundle.json'
    )
    console.log('new bundle generated')
    bundle = JSON.parse(mfs.readFileSync(bundlePath, 'utf-8'))
})

const handleSSR = async ctx => {
    if(!bundle) {
        ctx.body = 'please wait...'
        return
    }
    // vue-ssr-manifest.json 这个文件是客户端webpack [const VueClientPlugin = require('vue-server-renderer/client-plugin')]这个插件生成的
    const clientManifestResp = await axios.get('http://192.168.14.78:9001/vue-ssr-client-manifest.json')
    const clientManifest = clientManifestResp.data

    const template = fs.readFileSync(
        path.join(__dirname, '../server.template.ejs'),
        'utf-8'
    )
    // 生成一个可以直接调用render的function
    // 会自动生成一个带有script标签的js文件引用的字符串
    const renderer = VueServerRenderer.createBundleRenderer(bundle, {
        inject: false,
        clientManifest
    })
    await serverRender(ctx, renderer, template)
}

const router = new Router()

router.get('*', handleSSR)
module.exports = router